package com.tanhua.server.service;


import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.UsersApi;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.Contacts;
import com.tanhua.dubbo.server.pojo.Users;
import com.tanhua.server.pojo.Announcement;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.MessageAnnouncement;
import com.tanhua.server.vo.MessageLike;
import com.tanhua.server.vo.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class IMService {

    @Value("${tanhua.sso.url}")
    private String url;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private UserInfoService userInfoService;

    @Reference(version = "1.0.0")
    private UsersApi usersApi;

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    public boolean contactUser(Long friendUserId) {
        try {
            User user = UserThreadLocal.get();
            Users users = new Users();
            users.setUserId(user.getId());
            users.setFriendId(friendUserId);
            //到MongoDB中添加好友关系
            String result = usersApi.saveUsers(users);
            if (StringUtils.isEmpty(result))
                return false;
            //再在环信添加关系
            String targetUrl = url + "/user/huanxin/contacts/" + user.getId() + "/" + friendUserId;
            ResponseEntity<Void> responseEntity = this.restTemplate.postForEntity(targetUrl, null, Void.class);
            if (responseEntity.getStatusCodeValue() == 200)
                return true;
        } catch (RestClientException e) {
            e.printStackTrace();
        }
        return false;
    }

    //查询联系人列表
    public PageResult queryContactsList(Integer page, Integer pageSize, String keyword) {
        Long userId = UserThreadLocal.get().getId();
        List<Users> usersList = null;
        //判断是否是模糊查询
        if (StringUtils.isNotEmpty(keyword)) {
            //是,查询所有
            usersList = this.usersApi.queryAllUsersList(userId);
        } else {
            //分页查询
            usersList = this.usersApi.queryUsersList(userId, page, pageSize);
        }
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPages(0);
        pageResult.setCounts(0);
        if (CollectionUtils.isEmpty(usersList))
            return pageResult;
        //查询列表人详细信息
        Set<Long> userIds = usersList.stream().map(Users::getFriendId).collect(Collectors.toSet());
        List<UserInfo> userInfoList = null;
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(UserInfo::getUserId,userIds);
        if (StringUtils.isNotEmpty(keyword)) {
            //模糊查询,此处需要分页查询mysql
            wrapper.like(UserInfo::getNickName,keyword);
            IPage<UserInfo> infoIPage = new Page<>(page,pageSize);
            userInfoList = userInfoService.queryUserInfoList(wrapper,infoIPage);
        }else{
            userInfoList = userInfoService.queryUserInfoList(wrapper);
        }
        List<Contacts> contactsList = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            Contacts contacts = new Contacts();
            contacts.setAge(userInfo.getAge());
            contacts.setAvatar(userInfo.getLogo());
            contacts.setGender(userInfo.getSex().name().toLowerCase());
            contacts.setNickname(userInfo.getNickName());
            contacts.setUserId(String.valueOf(userInfo.getUserId()));
            contacts.setCity(StringUtils.substringBefore(userInfo.getCity(), "-"));
            contactsList.add(contacts);
        }
        pageResult.setItems(contactsList);
        return pageResult;

    }

    public PageResult queryMessageLikeList(Integer page, Integer pageSize) {
        return getPageResult(page,pageSize,1);
    }

    public PageResult queryMessageCommentList(Integer page, Integer pageSize) {
        return getPageResult(page,pageSize,2);
    }

    public PageResult queryMessageLoveList(Integer page, Integer pageSize) {
        return getPageResult(page,pageSize,3);
    }

    private PageResult getPageResult(Integer page, Integer pageSize, int type){
        PageResult pageResult = new PageResult();
        Long userId = UserThreadLocal.get().getId();
        List<Comment> commentList = quanZiApi.queryCommentListByUser(userId, type, page, pageSize);
        if (CollectionUtils.isEmpty(commentList)) {
            //查询结果为空,直接返回
            return pageResult;
        }
        Set<Long> usrIds = commentList.stream().map(Comment::getUserId).collect(Collectors.toSet());
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(UserInfo::getUserId,usrIds);
        List<UserInfo> userInfoList = userInfoService.queryUserInfoList(wrapper);
        ArrayList<MessageLike> list = new ArrayList<>();
        for (Comment comment : commentList) {
            for (UserInfo userInfo : userInfoList) {
                if (comment.getUserId().longValue() == userInfo.getUserId()){
                    MessageLike messageLike = new MessageLike();
                    messageLike.setAvatar(userInfo.getLogo());
                    messageLike.setCreateDate(new DateTime(comment.getCreated()).toString("yyyy-MM-dd HH:mm"));
                    messageLike.setNickname(userInfo.getNickName());
                    messageLike.setId(comment.getId().toHexString());
                    list.add(messageLike);
                }
            }
        }
        pageResult.setItems(list);
        return pageResult;
    }

    @Autowired
    private  AnnouncementService announcementService;

    public PageResult queryMessageAnnouncementList(Integer page, Integer pageSize) {
        IPage<Announcement> announcementPage = this.announcementService.queryList(page, pageSize);

        List<MessageAnnouncement> messageAnnouncementList = new ArrayList<>();

        for (Announcement record : announcementPage.getRecords()) {
            MessageAnnouncement messageAnnouncement = new MessageAnnouncement();
            messageAnnouncement.setId(record.getId().toString());
            messageAnnouncement.setTitle(record.getTitle());
            messageAnnouncement.setDescription(record.getDescription());
            messageAnnouncement.setCreateDate(new DateTime(record.getCreated()).toString("yyyy-MM-dd HH:mm"));

            messageAnnouncementList.add(messageAnnouncement);
        }

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPages(0);
        pageResult.setCounts(0);
        pageResult.setPagesize(pageSize);
        pageResult.setItems(messageAnnouncementList);

        return pageResult;
    }
}
